<template>
  <!-- #ifndef H5 -->
  <u-navbar title="预约发货单" fixed border leftIcon="" leftText=""></u-navbar>
  <!-- #endif -->
  <!-- #ifdef H5 -->
  <u-navbar title="预约发货单" fixed border @leftClick="navigateBack" @rightClick="navigateHome">
    <template #right>
      <u-icon name="home" size="24"></u-icon>
    </template>
  </u-navbar>
  <!-- #endif -->
  <view class="page_wrap_container" :style="{ paddingTop: NavBarHeight + 'px' }">
    <scroll-view :style="{ height: windowHeight + 'px' }" scroll-y enable-flex :show-scrollbar="false"
      class="purchase_page_list" v-if="pagination.listData && pagination.listData.length > 0" @scrolltolower="loadMore">
      <view class="list_item" v-for="item in pagination.listData" :key="item.id">
        <view class="list_item_header">
          <view class="lih_title">{{ item.reserveInvoiceCode }}</view>
          <view class="lih_tag"><up-tag :text="item.reserveInvoiceStatusName"
              :color="Send_COLOR_MAP[item.reserveInvoiceStatus]"
              :borderColor="Send_COLOR_MAP[item.reserveInvoiceStatus]" plain></up-tag></view>
        </view>
        <view class="list_item_info">
          <view class="lif_item">
            <view class="lifi_top">预约数量：</view>
            <view class="lifi_main li-flex">
              <view>{{ item.totalScheduleQty || '-' }}</view>
              <view v-if="item.totalScheduleQty && item.totalScheduleQty > 0" class="viewit" @click="viewMore(item)">
                查看明细</view>
            </view>
          </view>
          <view class="lif_item">
            <view class="lifi_top">预计到货时间：</view>
            <view class="lifi_main">{{ item.estimatedArrivalTimeStart || '-' }}</view>
          </view>
          <view class="lif_item">
            <view class="lifi_top">到货数量：</view>
            <view class="lifi_main">{{ item.totalArriveQty || '-' }}</view>
          </view>
          <view class="lif_item">
            <view class="lifi_top">最近到货时间：</view>
            <view class="lifi_main">{{ item.lastArrivalTime || '-' }}</view>
          </view>

        </view>
        <!-- #ifndef H5 -->
        <view class="actions_box" @click.stop="checkOrder(item)" v-if="item.reserveInvoiceStatus == 1">
          <view class="ab_btn">审核</view>
        </view>
        <!-- #endif -->
        <view class="actions_box" @click.stop="checkSend(item)" v-if="item.reserveInvoiceStatus == 2">
          <view class="ab_btn">确认发货</view>
        </view>
      </view>
      <view class="has_data_text">
        <view class="no_more" v-if="!pagination.finished">加载中～</view>
        <view class="no_more" v-else>没有数据了～</view>
      </view>
      <view :style="{ height: '50px'}"></view>
    </scroll-view>
    <view class="empty_wrap" :style="{ height: windowHeight + 'px' }" v-else>
      <up-empty mode="order" text="暂无数据～">
      </up-empty>
    </view>
    <up-popup :show="popupFormSendShow" :round="10" @close="SendFormClose" closeOnClickOverlay>
      <view class="status_wrap_pop">
        <view class="pop_actions">
          <view class="reset_btn" @click="SendFormClose">关闭</view>
          <view class="confirm_btn" @click="popFormSendSave">保存</view>
        </view>
        <view class="form_wrap">
          <up-form labelAlign="right" ref="SendFormRef" :model="modalSend" labelWidth="130" :rules="formSendRules">
            <up-form-item label="预计到货时间：" prop="Send.estimatedArrivalTime" borderBottom>
              <up-cell :titleStyle="{ color: '#c1c4cc', fontSize: '15px' }" @click="handleShowDatePicker"
                :title="modalSend.Send.estimatedArrivalTime" :isLink="true" arrow-direction="down"
                :border="false"></up-cell>
            </up-form-item>
            <up-form-item label="承运商：" prop="Send.license" borderBottom>
              <up-cell :titleStyle="{ color: '#c1c4cc', fontSize: '15px' }" @click="handleShowColumnsPicker"
                :title="modalSend.Send.transporterName" :isLink="true" arrow-direction="down" :border="false"></up-cell>
            </up-form-item>
            <up-form-item label="承运单号：" prop="Send.transportSn" borderBottom>
              <up-input v-model="modalSend.Send.transportSn" placeholder="请输入承运单号"></up-input>
            </up-form-item>
            <up-form-item label="联系方式：" prop="Send.contactInfo" borderBottom>
              <up-input v-model="modalSend.Send.contactInfo" placeholder="请输入联系方式"></up-input>
            </up-form-item>
            <up-form-item label="司机姓名：" prop="Send.driverName" borderBottom>
              <up-input v-model="modalSend.Send.driverName" placeholder="请输入司机姓名"></up-input>
            </up-form-item>
            <up-form-item label="车牌号：" prop="Send.license" borderBottom>
              <up-input v-model="modalSend.Send.license" placeholder="请输入车牌号"></up-input>
            </up-form-item>
          </up-form>
        </view>
      </view>
    </up-popup>
    <up-popup :show="popListShow" :round="10" @close="popListClose" closeOnClickOverlay closeable>
      <view class="detail_title">明细</view>
      <scroll-view class="list_item_img_box" :style="{ height: '400px' }" scroll-y enable-flex :show-scrollbar="false">
        <view class="liib_item" v-for="it in viewList" :key="it.id">
          <view class="liibi_main">
            <view class="lm_imgbox">
              <image :src="it?.productSimpleVO?.imageUrl" alt="" />
            </view>
            <view class="lm_textbox">
              <view class="liibi_title_box">
                <view class="left_main_title text_ellipsis">{{ it?.productSimpleVO?.spuName || '-' }}</view>
                <view class="price_num">预约数量：{{ it.scheduleQty || '-' }}</view>
              </view>
              <view class="subtitle">款式编码：{{ it?.productSimpleVO?.spuCode || '-' }}</view>
              <view class="subtitle">商品条码：{{ it?.productSimpleVO?.skuCode || '-' }}</view>
              <view class="liibi_title_box">
                <view class="subtitle left_sub_title text_ellipsis">{{ it?.productSimpleVO?.colorDetailName || '-' }}；{{
    it?.productSimpleVO?.size }}</view>
                <view class="price_num">到货数量：{{ it.arriveQty || '-' }}</view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </up-popup>
    <up-datetime-picker ref="datetimePickerRef" closeOnClickOverlay :show="datePickerShow"
      v-model="modalSend.Send.estimatedArrivalTime" mode="date" :formatter="formatter" @confirm="datePickerConfirm"
      @cancel="datePickerClose" @close="datePickerClose"></up-datetime-picker>
    <up-modal :show="modalShow" showCancelButton closeOnClickOverlay :title="modalTitle" @cancel="modalCancel"
      @close="modalCancel" @confirm="modalConfirm"></up-modal>
    <up-picker :show="TransSelectShow" closeOnClickOverlay :columns="Transcolumns" keyName="label"
      @confirm="onTransconfirm" @cancel="onTranscancel" @close="onTranscancel"></up-picker>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import HTTP from "@/utils/http"
import dayjs from "dayjs"
import { reactive } from "vue";
import type { PurchaseListType } from "./types"
import { onLoad } from "@dcloudio/uni-app";
import useScreenSize from "@/hooks/useScreenSize";
const { windowHeight, NavBarHeight, isIphoneX } = useScreenSize()
//获取页面 purchaseOrderCode
let purchaseOrderCode: string
onLoad((options: any) => {
  purchaseOrderCode = options.purchaseOrderCode || ""
})
const navigateBack = () => {
  uni.navigateBack()
}
const navigateHome = () => {
  uni.switchTab({ url: "/pages/index/index" })
}
const Send_COLOR_MAP: { [k: number | string]: any } = {
  1: '#13c2c2',
  2: '#1677ff',
  3: '#1d39c4',
  4: '#52c41a',
  5: '#ff4d4f',
  null: '#1677ff'
}
const viewList = ref<any[]>([])
const popListShow = ref(false)
const popListClose = () => {
  popListShow.value = false
}
const viewMore = (info: any) => {
  if (info.detailVOS && info.detailVOS.length > 0) {
    viewList.value = info.detailVOS
    popListShow.value = true
  }
}
// actions
const currentInfo = ref<Record<string, any>>({})
const checkOrder = (info: PurchaseListType) => {
  currentInfo.value = info
  modalShow.value = true
}
const checkSend = (info: PurchaseListType) => {
  currentInfo.value = info
  popupFormSendShow.value = true
}
//Modal
const modalShow = ref(false)
const modalTitle = ref("确认要提交审核吗？")
const modalCancel = () => {
  modalShow.value = false
  currentInfo.value = {}
}
const modalConfirm = () => {
  HTTP.POST({
    url: "sop/sop/reserveInvoice/batchAudit",
    isJson: true,
    data: { reserveInvoiceCodes: [currentInfo.value?.reserveInvoiceCode] },
    success: (res: any) => {
      if (res.code == 200) {
        uni.showToast({
          title: '操作成功',
          icon: 'none',
        })
        resetListData()
      }
    },
    complete: () => {
      modalCancel()
    }
  })
}
//承运商ColumnsPicker
const handleShowColumnsPicker = () => {
  TransSelectShow.value = true
}
const TransSelectShow = ref(false)
const Transcolumns = ref([[]])
const onTransconfirm = (event: any) => {
  modalSend.Send.transporterId = event?.value[0]?.value
  modalSend.Send.transporterName = event?.value[0]?.label
  TransSelectShow.value = false
}
const onTranscancel = () => {
  TransSelectShow.value = false
}
//DatePicker
const datetimePickerRef = ref<any>(null);
const formatter = (type: string, value: string) => {
  if (type === 'year') {
    return `${value}年`;
  }
  if (type === 'month') {
    return `${value}月`;
  }
  if (type === 'day') {
    return `${value}日`;
  }
  return value;
};
const datePickerShow = ref(false)
const handleShowDatePicker = () => {
  datePickerShow.value = true
}
const datePickerConfirm = (event: any) => {
  datePickerShow.value = false
  modalSend.Send.estimatedArrivalTime = dayjs(event.value).format("YYYY-MM-DD")
}
const datePickerClose = () => {
  datePickerShow.value = false
}
//popupFormSendShow
const SendFormRef = ref<any>(null)
const popupFormSendShow = ref(false)
const SendFormClose = () => {
  popupFormSendShow.value = false
  SendFormRef.value.resetFields()
  modalSend.Send = {
    estimatedArrivalTime: dayjs().format("YYYY-MM-DD"),
    transporterId: "",
    transporterName: "请选择承运商",
    transportSn: "",
    contactInfo: "",
    driverName: "",
    license: ""
  }
}
const popFormSendSave = () => {
  SendFormRef.value.validate().then(() => {
    HTTP.POST({
      url: "sop/sop/reserveInvoice/delivery",
      isJson: true,
      data: { ...modalSend.Send, reserveInvoiceCode: currentInfo.value.reserveInvoiceCode },
      success: (res: any) => {
        if (res.code == 200) {
          uni.showToast({
            title: '操作成功',
            icon: 'none',
          })
          resetListData()
        }
      },
      complete: () => {
        SendFormClose()
      }
    })
  })
}
//search
const resetListData = () => {
  resetPagination()
  getListData()
}
const resetPagination = () => {
  pagination.current = 1
  pagination.size = 10
  pagination.listData = []
  pagination.allcurrent = 1
  pagination.finished = false
}
//列表数据
onMounted(() => {
  datetimePickerRef.value && datetimePickerRef.value?.setFormatter(formatter);
  getListData()
  getTransColumns()
})
const getTransColumns = () => {
  HTTP.POST({
    url: "sop/sop/supplierInfo/pageList",
    isJson: true,
    data: { supplierClassificationCode: "07" },
    success: (res: any) => {
      if (res.code == 200) {
        if (res.data.list && res.data.list.length > 0) {
          Transcolumns.value[0] = res.data.list.map((item: any) => {
            return {
              label: item.supplierName,
              value: item.supplierId
            }
          })
        }
      }
    }
  })

}
const pagination = reactive<{ current: number, size: number, listData: PurchaseListType[], allcurrent: number, finished: boolean }>({
  current: 1, size: 10, listData: [], allcurrent: 1, finished: false
})
const getListData = async () => {
  if (pagination.current > pagination.allcurrent) return;
  const params = {
    current: pagination.current,
    size: pagination.size,
    purchaseOrderCode
  }
  HTTP.POST({
    url: "sop/sop/reserveInvoice/query",
    isJson: true,
    data: params,
    success: (res: any) => {
      if (res.code == 200) {
        pagination.allcurrent = res.data.pageNum || 1
        pagination.listData = pagination.listData.concat(res?.data?.list || [])
        if (pagination.current + 1 > pagination.allcurrent) pagination.finished = true
        else pagination.finished = false
      } else {
        pagination.listData = []
      }
    }
  })
}
const loadMore = () => {
  pagination.current = pagination.current + 1
  getListData()
}
//form
const modalSend = reactive({
  Send: {
    estimatedArrivalTime: dayjs().format("YYYY-MM-DD"),
    transporterId: "",
    transporterName: "请选择承运商",
    transportSn: "",
    contactInfo: "",
    driverName: "",
    license: ""
  }
})
const formSendRules = {
  'Send.estimatedArrivalTime': { type: "string", required: true, message: "请选择预计到货时间", },
}
</script>
<style lang="scss" scoped>
.page_wrap_container {
  display: flex;
  flex-direction: column;

  .purchase_page_list {

    .has_data_text {
      color: #aaa;
      text-align: center;
    }

    .list_item {
      margin: 24rpx 24rpx 0;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      margin-bottom: 24rpx;
      border-radius: 18rpx;
      box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.08);
      overflow: hidden;

      .list_item_header {
        padding: 0 20rpx;
        height: 80rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .lih_title {
          flex: 1;
          font-weight: 500;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
          font-size: 34rpx;
        }

        .lih_tag {
          flex-shrink: 0;
        }
      }

      .list_item_info {
        display: flex;
        flex-direction: column;
        padding: 12rpx 20rpx;

        .lif_item {
          flex-shrink: 0;
          display: flex;
          flex-direction: row;
          margin-bottom: 12rpx;
          position: relative;
          flex-wrap: wrap;

          .li-flex {
            display: flex;
            align-items: center;

            .viewit {
              margin-left: 30rpx;
              color: $uni-color-primary;
              font-size: 26rpx;
              border-left: 1px solid #a1a1a1;
              padding: 0 30rpx;
            }
          }

          .lifi_top {
            flex-shrink: 0;
            margin-right: 12rpx;
            color: #888;
          }

          .lifi_main {
            flex: 1;
            flex-shrink: 0;
            color: #333;
            word-break: break-all;
            overflow-wrap: break-word;
          }

          .lifi_main_text_ellipsis {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }

      .actions_box {
        border-top: 1px solid #f1f1f1;
        padding: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        .ab_btn {
          font-size: 30rpx;
          padding: 10rpx;
          color: $uni-color-primary;
        }
      }
    }
  }

  .empty_wrap {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
}

.status_wrap_pop {
  padding: 30rpx;
  min-height: 300rpx;

  .form_wrap {
    width: 100%;
    padding: 24rpx 30rpx;
  }

  .pop_actions {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .reset_btn {
      color: #888;
      padding: 12rpx;
    }

    .confirm_btn {
      color: $uni-color-primary;
      padding: 12rpx;
    }
  }

  .status_item {
    .status_item_title {
      padding: 30rpx 0;
      font-size: 36rpx;
      font-weight: 400;
      color: #333;
    }

    .status_item_btns_box {
      display: flex;
      flex-wrap: wrap;
      gap: 18rpx;

      .status_item_btn {
        border: 1px solid #ddd;
        padding: 10rpx 20rpx;
        color: #666;
      }

      .status_item_btn_active {
        border: 1px solid $uni-color-primary;
        background-color: $uni-color-primary;
        color: #fff;
      }
    }
  }
}

.detail_title {
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-weight: 500;
}

.list_item_img_box {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  margin: 40rpx 0;
  padding: 0 20rpx;

  .liib_item {
    display: flex;
    flex-direction: column;
    margin-bottom: 12rpx;
    box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.08);
    padding: 30rpx 20rpx;
    border-radius: 20rpx;
    border: 1px solid #f1f2f3;

    .liibi_main {
      display: flex;

      .lm_imgbox {
        width: 120rpx;
        height: 120rpx;
        margin-top: 8rpx;
        border-radius: 6rpx;
        overflow: hidden;
        flex-shrink: 0;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .lm_textbox {
        flex: 1;
        padding-left: 12rpx;
        font-size: 28rpx;

        .liibi_title_box {
          font-size: 30rpx;
          color: #333;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .left_main_title {
            max-width: 400rpx;
            font-weight: 500;
          }

          .left_sub_title {
            max-width: 400rpx;
          }

          .text_ellipsis {
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }

          .price_num {
            font-weight: 500;
            font-size: 28rpx;
            color: #888;
          }
        }

        .subtitle {
          color: #888;
          font-size: 28rpx;
        }

        .liibi_btm {
          display: flex;
          align-items: center;
          justify-content: space-between
        }

      }
    }
  }
}
</style>
